﻿//-----------------------------------------------------------------------
// <copyright file="CartPurchaseViewModel.cs" company="FER">
//     Copyright (c) All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace NMBP.View.ViewModel
{
    using System;
    using System.Collections.Generic;

    using GalaSoft.MvvmLight;
    using GalaSoft.MvvmLight.Command;
    using GalaSoft.MvvmLight.Messaging;

    using NMBP.DAL;
    using NMBP.Models;
    using NMBP.Models.Enums;
    using NMBP.ViewModels.Dialogs;

    /// <summary>
    /// Initializes a new instance of the CartPurchaseViewModel class
    /// </summary>
    public class CartPurchaseViewModel : ViewModelBase
    {
        #region Bindable Fields
        /// <summary>
        /// Gets or sets list of products in cart
        /// </summary>
        private List<Product> cartProducts;

        /// <summary>
        /// Gets or sets current datetime
        /// </summary>
        private string dateTime;

        /// <summary>
        /// Gets or sets total sum to pay
        /// </summary>
        private float totalSum;

        /// <summary>
        /// Gets or sets customer name
        /// </summary>
        private string customerName;

        /// <summary>
        /// Gets or sets customer surname
        /// </summary>
        private string customerSurname;

        /// <summary>
        /// Gets or sets selected payment method
        /// </summary>
        private string selectedPaymentMethod;

        /// <summary>
        /// Gets or sets a value indicating whether buy is enabled
        /// </summary>
        private bool isBuyEnabled;

        /// <summary>
        /// Gets or sets list of available payment methods
        /// </summary>
        private List<string> availablePaymentMethod;

        /// <summary>
        /// Action raised when view model needs to be initialized
        /// </summary>
        private Action<Cart> initViewModel;

        /// <summary>
        /// Gets or sets recieved cart
        /// </summary>
        private Cart recievedCart;
        #endregion

        /// <summary>
        /// Initializes a new instance of the CartPurchaseViewModel class
        /// </summary>
        public CartPurchaseViewModel()
        {
            this.initViewModel = new Action<Cart>(this.InitializeViewModel);
            Messenger.Default.Register<Cart>(this, "InitializeCartPurchase", this.initViewModel);

            this.CancelOrder = new RelayCommand(
                () =>
                    {
                        Messenger.Default.Send(this.recievedCart.Customer, "OpenCustomerWindow");
                    });

            this.MakeOrder = new RelayCommand(
                () =>
                    {
                        string orderCode = String.Format("{0:yyyyMMddHHmmss}", DateTime.Now);
                        Order order = new Order
                            {
                                Cart = this.recievedCart,
                                Date = String.Format("{0:s}", DateTime.Now),
                                IsDone = false,
                                SupplierName = string.Empty,
                                PaymentMethod = this.DeterminePreferedPayment(),
                                Code = orderCode,
                                WorkerUsername = string.Empty
                            };

                        this.recievedCart.IsOrdered = true;
                        order.Cart.Customer.IsInCart = true;
                        this.DbFacade.SaveOrder(order);

                        this.DialogService.ShowMessage("Narudžba uspješno provedena!", MessageType.INFO);
                        Messenger.Default.Send(this.recievedCart.Customer, "OpenCustomerWindow");
                    });
        }

        #region Bindable Properties
        /// <summary>
        /// Gets or sets list of products in cart
        /// </summary>
        public List<Product> CartProducts
        {
            get
            {
                return this.cartProducts;
            }

            set
            {
                this.cartProducts = value;
                this.RaisePropertyChanged("CartProducts");
            }
        }

        /// <summary>
        /// Gets or sets current datetime
        /// </summary>
        public string DateOfPurchase
        {
            get
            {
                return this.dateTime;
            }

            set
            {
                this.dateTime = value;
                this.RaisePropertyChanged("DateOfPurchase");
            }
        }

        /// <summary>
        /// Gets or sets instance of db facade
        /// </summary>
        public IDbFacade DbFacade { get; set; }

        /// <summary>
        /// Gets or sets instance of dialog service
        /// </summary>
        public IDialogService DialogService { get; set; }

        /// <summary>
        /// Gets or sets total sum to pay
        /// </summary>
        public float TotalSum
        {
            get
            {
                return this.totalSum;
            }

            set
            {
                this.totalSum = value;
                this.RaisePropertyChanged("TotalSum");
            }
        }

        /// <summary>
        /// Gets or sets customer name
        /// </summary>
        public string CustomerName
        {
            get
            {
                return this.customerName;
            }

            set
            {
                this.customerName = value;
                this.RaisePropertyChanged("CustomerName");
            }
        }

        /// <summary>
        /// Gets or sets customer surname
        /// </summary>
        public string CustomerSurname
        {
            get
            {
                return this.customerSurname;
            }

            set
            {
                this.customerSurname = value;
                this.RaisePropertyChanged("CustomerSurname");
            }
        }

        /// <summary>
        /// Gets or sets selected payment method
        /// </summary>
        public string SelectedPaymentMethod
        {
            get
            {
                return this.selectedPaymentMethod;
            }

            set
            {
                this.selectedPaymentMethod = value;
                this.RaisePropertyChanged("SelectedPaymentMethod");
            }
        }

        /// <summary>
        /// Gets or sets list of available payment methods
        /// </summary>
        public List<string> AvailablePaymentMethod
        {
            get
            {
                return this.availablePaymentMethod;
            }

            set
            {
                this.availablePaymentMethod = value;
                this.RaisePropertyChanged("AvailablePaymentMethod");
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether buy is enabled
        /// </summary>
        public bool IsBuyEnabled
        {
            get
            {
                return this.isBuyEnabled;
            }

            set
            {
                this.isBuyEnabled = value;
                this.RaisePropertyChanged("IsBuyEnabled");
            }
        }
        #endregion

        #region Bindable Commands
        /// <summary>
        /// Gets a command raised when make order button is clicked
        /// </summary>
        public RelayCommand MakeOrder { get; private set; }

        /// <summary>
        /// Gets a command raised when cancel order button is clicked
        /// </summary>
        public RelayCommand CancelOrder { get; private set; }

        #endregion

        /// <summary>
        /// Initializes view model
        /// </summary>
        /// <param name="cart">Cart to initialize model</param>
        private void InitializeViewModel(Cart cart)
        {
            this.recievedCart = cart;
            this.DialogService = new DialogService();
            if (this.DbFacade == null)
            {
                this.DbFacade = new DbFacade();
            }

            this.CartProducts = this.recievedCart.Products;
            this.CustomerName = this.recievedCart.Customer.Name;
            this.CustomerSurname = this.recievedCart.Customer.Surname;
            this.TotalSum = this.recievedCart.TotalPrice;
            this.AvailablePaymentMethod = new List<string>() { "Gotovina", "Kartica" };
            this.SelectedPaymentMethod = cart.Customer.PrefferedPayment == PaymentMethod.Cash
                                             ? this.AvailablePaymentMethod[0]
                                             : this.AvailablePaymentMethod[1];

            if (this.TotalSum != 0)
            {
                this.IsBuyEnabled = true;
            }

            this.DateOfPurchase = String.Format("{0:dd.MM.yyyy.}", DateTime.Now);
        }

        /// <summary>
        /// Determines selected payment method
        /// </summary>
        /// <returns>Payment method</returns>
        private PaymentMethod DeterminePreferedPayment()
        {
            return this.SelectedPaymentMethod == "Gotovina" ? PaymentMethod.Cash : PaymentMethod.Card;
        }
    }
}
